<template>
  <div>
    <h1>{{ unSelectSaleAttr }}</h1>
    <el-form ref="form" label-width="80px" :model="spuForm">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spuForm.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请您选择品牌" v-model="spuForm.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="(tm, index) in trademarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="spu描述">
        <el-input
          type="textarea"
          placeholder="spu描述"
          v-model="spuForm.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="spuImageList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <!-- 目前select这里仅仅只是展示数据。并未做收集数据业务 -->
        <el-select :placeholder="unSelectSaleAttr.length > 0 ? `还有${unSelectSaleAttr.length}个未选择`: '没有啦'" v-model="attrIdAndName">
          <el-option
            :label="unselect.name"
            :value="`${unselect.id}:${unselect.name}`"
            v-for="(unselect, index) in unSelectSaleAttr"
            :key="unselect.id"
          ></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" @click="addNewSaleAttr" :disabled="!attrIdAndName ? true : false">添加销售属性</el-button>
        <el-table style="width: 100%" border :data="spuForm.spuSaleAttrList">
          <el-table-column type="index" label="序号" align="center" width="80">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="180">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                :key="saleAttrValue.id"
                v-for="(saleAttrValue,index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index,1)"
              >
                {{ saleAttrValue.saleAttrValueName}}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                ref="saveTagInput"
                size="small"
                v-model="row.inputValue"
                @blur="changeInputVisible(row)"
                @keyup.native.enter="changeInputVisible(row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="180">
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save" :disabled="!spuForm.spuName">保存</el-button>
        <el-button @click="changeScene">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      //照片墙将来可能用到的属性
      dialogImageUrl: "",
      dialogVisible: false,
      //存储spu信息
      spuForm: {
        spuName: "", //类的名字
        category3Id: "", //三级分类的ID
        description: "", //描述
        tmId: "", //品牌的id
        spuImageList: [
          //收集照片墙图片的数据
        ],
        spuSaleAttrList: [],
      },
      //照片墙
      spuImageList: [],
      //品牌
      trademarkList: [],
      //全部销售属性
      saleAttrList: [],
      //收集新增的销售属性与id
      attrIdAndName:''
    };
  },
  methods: {
    //照片墙点击删除按钮出发
    handleRemove(file, fileList) {
      //收集照片墙的数据
      this.spuImageList = fileList;
    },
    //点击照片墙图片放大的时候会出发
    handlePictureCardPreview(file) {
      //存储要显示放大的图片地址
      this.dialogImageUrl = file.url;
      //显示放大镜
      this.dialogVisible = true;
    },
    //图片上传成功的回调
    handleSuccess(response, file, fileList) {
      //fileList:当图片上传成功以后，照片墙全部数据！！！！
      this.spuImageList = fileList;
    },
    //取消按钮的回调
    changeScene() {
      //触发自定义事件:通知父组件切换场景为0
      this.$emit("changeScene",{scene:0});
      //清除数据
      //组件实例身上有一个属性$options,可以获取当前组件的配置项
      Object.assign(this._data,this.$options.data());
    },
    //获取spu等相关数据的方法
    async getSpuInfoList(spu) {
      //获取当前类的信息
      let promise1 = this.$API.spu.reqSpuInfoById(spu.id);
      //获取当前类的图片
      let promise2 = this.$API.spu.reqSpuImageList(spu.id);
      //获取下拉菜单品牌信息
      let promise3 = this.$API.spu.reqTradeMarkList();
      //获取全部的销售属性【3个：颜色、尺码、版本】
      let promise4 = this.$API.spu.reqSaleAttrList();
      //统一处理
      let result = await Promise.all([promise1, promise2, promise3, promise4]);
      //相应存储数据---当前组件身上
      //当前类的信息
      this.spuForm = result[0].data;
      //照片墙的数据
      this.spuImageList = result[1].data;
      //切记照片墙的数据：name与url字段
      this.spuImageList = this.spuImageList.map((item) => {
        return {
          ...item,
          name: item.imgName,
          url: item.imgUrl,
        };
      });
      //品牌的信息
      this.trademarkList = result[2].data;
      //全部销售属性
      this.saleAttrList = result[3].data;
    },
    //添加新增销售属性值按钮的回调
    addSaleAttrValue(row){
       //添加一个响应式属性inputVisible，控制button与input切换属性
       this.$set(row,'inputVisible',true);
       //在给当前销售属性在添加一个响应式属性
       this.$set(row,'inputValue','');
    },
    //输入框失去焦点的方法
    changeInputVisible(row){
       //需要向销售属性的属性值列表数组里面添加新增的属性值
       const {baseSaleAttrId,inputValue} = row;
        //判断:属性值不能为空
       if(inputValue.trim()==''){
         this.$message({type:'warning',message:'属性值不能为空'});
         return;
       }
       //查找是否有重复的属性值
       let repeat = row.spuSaleAttrValueList.find(item=>{
            //代表重复了
            return inputValue==item.saleAttrValueName;
       });
       //重复
       if(repeat){
         this.$message({type:'warning',message:'添加属性值不能重复'});
         return;
       }
       //创建一个新的销售属性值---对象
       let newSaleAttrValue = {baseSaleAttrId,saleAttrValueName:inputValue};
       //添加到销售属性值的数组里面
       row.spuSaleAttrValueList.push(newSaleAttrValue);
       row.inputVisible = false; 
    },
    //添加新的销售属性
    addNewSaleAttr(){
      //整理数据:第一个销售属性的id 、新增的销售属性名
      const [baseSaleAttrId,saleAttrName]  = this.attrIdAndName.split(':');
      //准备对象---一个销售属性,最后的K用与将来收集属性值
      let newSaleAttr = {baseSaleAttrId,saleAttrName,spuSaleAttrValueList:[]};
      //添加到当前类的销售属性的数组里面
      this.spuForm.spuSaleAttrList.push(newSaleAttr);
      //清空收集的数据
      this.attrIdAndName = '';

    },
    //保存按钮:可以是添加|修改
    async save(){
       //整理参数
       this.spuForm.spuImageList = this.spuImageList.map(item=>{
           return {
             ...item,
             imgName:item.name,
             imgUrl:(item.response && item.response.data) || item.url
           }
       })
       //发请求
       try{
         await this.$API.spu.reqAddOrUpdateSpu(this.spuForm);
         //保存成功提示信息
         this.$message({type:'success',message:'保存成功'});
         //通知父组件切换场景
         this.$emit('changeScene',{scene:0,flag:this.spuForm.id?'update':'add'});
       }catch(error){

       }
       //请求成功
       //请求失败
    },
    //添加SPU按钮点击的时候，需要发请求的函数
    async initData(category3Id){
      //收集父亲给的三级分类的id
      this.spuForm.category3Id = category3Id;
      //获取下拉菜单品牌信息
      let promise1 = this.$API.spu.reqTradeMarkList();
      //获取全部的销售属性【3个：颜色、尺码、版本】
      let promise2 = this.$API.spu.reqSaleAttrList();
      let result = await Promise.all([promise1, promise2]);
      //品牌的信息
      this.trademarkList = result[0].data;
      //全部销售属性
      this.saleAttrList = result[1].data;
    }
  },
  computed: {
    //计算出未选择的销售属性
    unSelectSaleAttr() {
      // //全部的销售属性
      // console.log(this.saleAttrList);
      // //当前类已有的销售属性
      // console.log(this.spuForm.spuSaleAttrList);
      //item->尺寸->颜色->版本
      //颜色
      return this.saleAttrList.filter((item) => {
        return this.spuForm.spuSaleAttrList.every((spu) => {
          return item.name != spu.saleAttrName;
        });
      });
    },
  },
};
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
